//index.js
//获取应用实例
const app = getApp()
import api from '../../api/index.js'
const {request} = require("../../utils/wx-api.js")
// console.log(request);
Page({
  data: {
    banner:'',
    channel:[
      {
        name:'家居',
        imgUrl:'../../assets/images/house.png'
      },
      {
        name: '餐厨',
        imgUrl: '../../assets/images/kit.png'
      },
      {
        name: '配件',
        imgUrl: '../../assets/images/mountings.png'
      },
      {
        name: '服装',
        imgUrl: '../../assets/images/clothes.png'
      },
      {
        name: '志趣',
        imgUrl: '../../assets/images/bent.png'
      }
    ],
    newGoodsList:'',
    hotGoodsList:'',
    brandList:''
  },
  toDetail(e){   //跳转到详情页
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../detail/detail?id=${id}`,
      success(res){
        // console.log(e);
      }
    })
  },
  onShow: function () {
    let that = this;
    //读取缓存数据
    let indexData = wx.getStorageSync("indexData");
    if(indexData){
      // 使用本地缓存
      // console.log(indexData);
      this.setData({
        banner:indexData.banner,
        newGoodsList: indexData.newGoodsList,
        hotGoodsList: indexData.hotGoodsList,
        brandList: indexData.brandList
      })
    }else {
      // wx.request({
      //   url: api.index,
      //   success: function (res) {
      //     console.log(res);
      //     // 缓存数据(同步接口)
      //     wx.setStorageSync("indexData", res.data.data);
      //     indexData = wx.getStorageSync("indexData");
      //     console.log(indexData);
      //     that.setData({
      //       banner:indexData.banner
      //     })
      //   },
      //   fail: function (err) {
      //     console.log(err);
      //   }
      // })
      //基于promise封装的方法，避免回调地狱
      request({url:api.index})
      .then(res=>{
        console.log(res);
        // 缓存数据(同步接口)
        wx.setStorageSync("indexData", res.data.data);
        indexData = wx.getStorageSync("indexData");
        console.log(indexData);
        that.setData({
          banner: indexData.banner,
          newGoodsList: indexData.newGoodsList,
          hotGoodsList: indexData.hotGoodsList,
          brandList: indexData.brandList
        })
      })
      .catch(err=>{
        console.log(err);
      })
    }
  }
})
